package com.heiye.blog.ai.strategy.text.impl;

import com.heiye.blog.ai.advisor.DashScopeAdvisor;
import com.heiye.blog.ai.enums.TextModelTypeEnum;
import com.heiye.blog.ai.helper.DashScopeAdvisorHelper;
import com.heiye.blog.ai.model.dashscope.DashScopeChatClient;
import com.heiye.blog.ai.model.dashscope.DashScopeChatOptions;
import com.heiye.blog.ai.model.dto.AIChatRequest;
import com.heiye.blog.ai.model.vo.AIResponse;
import com.heiye.blog.ai.model.vo.AiChatReqVO;
import com.heiye.blog.ai.strategy.text.TextModelStrategy;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author: heiye
 * @date: 2025/11/10 下午3:57
 * @version: v1.0.0
 * @description: 基于百炼模型调用 DeepSeek-V3.2-Exp 模型
 */
@Slf4j
@Component
public class DashScopeDeepSeeKV3_2Strategy implements TextModelStrategy {

    @Value("${spring.ai.dashscope.api-key}")
    private String apiKey;

    @Resource
    private DashScopeAdvisorHelper dashScopeAdvisorHelper;

    /**
     * 获取存储类型枚举
     *
     * @return TextModelTypeEnum
     */
    @Override
    public TextModelTypeEnum getTextModelType() {
        return TextModelTypeEnum.DASH_SCOPE_DEEPSEEK_V3_2_EXP;
    }

    /**
     * 处理流式响应
     *
     * @param aiChatRequest
     * @return
     */
    @Override
    public Flux<AIResponse> handleStreamResponse(AIChatRequest aiChatRequest) {
        // 对参数进行审查
        reviewAndOptimizeRequest(aiChatRequest);
        // 用户消息
        String userMessage = aiChatRequest.getUserMessage();
        // 是否启用深度思考
        Boolean enableThink = aiChatRequest.getThinkEnable();

        // 构建 dashScopeChatClient
        DashScopeChatClient dashScopeChatClient = DashScopeChatClient.builder()
                .options(DashScopeChatOptions.builder()
                        .apiKey(apiKey)
                        .networkSearch(aiChatRequest.getNetworkSearch())
                        .model(getTextModelType().getType())
                        .incrementalOutput(aiChatRequest.getIncrementalOutput())
                        .temperature((Objects.nonNull(aiChatRequest.getTemperature()) ? Float.parseFloat(aiChatRequest.getTemperature().toString()) : null))
                        .enableThink(enableThink)
                        .build())
                .userMessage(userMessage)
                .build();

        // 构建 Advisor
        List<DashScopeAdvisor> dashScopeAdvisors = dashScopeAdvisorHelper.buildDashScopeAdvisors(aiChatRequest);

        // 添加 Advisor
        dashScopeChatClient.advisors(dashScopeAdvisors);

        // 使用原子布尔值跟踪分隔线状态（每个请求独立）
        AtomicBoolean needSeparator = new AtomicBoolean(true);

        return dashScopeChatClient.stream()
                .mapNotNull(response -> {
                    // 获取推理内容
                    String reasoningContent = response.getOutput().getChoices().get(0).getMessage().getReasoningContent();

                    // 推理结束后的正式回答
                    String text = response.getOutput().getChoices().get(0).getMessage().getContent();

                    // 是否是正式回答
                    boolean isTextResponse = false;

                    // 若推理内容有值，则响应推理内容，否则，说明推理结束了，响应正式回答
                    String rawContent;
                    if (enableThink && StringUtils.isNotEmpty(reasoningContent)) {
                        rawContent = reasoningContent;
                    } else {
                        rawContent = text;
                        isTextResponse = true;
                    }

                    // 在正式回答内容之前，添加一个回车
                    if (enableThink
                            && isTextResponse
                            && needSeparator.compareAndSet(true, false)) {
                        rawContent = "\n" + rawContent;
                    }

                    return AIResponse.builder()
                            .v(rawContent)
                            .build();
                });
    }

    /**
     * 对参数进行审查
     *
     * @param aiChatRequest
     * @return
     */
    @Override
    public void reviewAndOptimizeRequest(AIChatRequest aiChatRequest) {
        // https://docs.cloud.google.com/vertex-ai/generative-ai/docs/thinking?hl=zh-cn#budget
        // 获取模型温度
//        Double temperature = aiChatRequest.getTemperature();
//
//        // 如果没设置温度则设置默认温度
//        if (Objects.isNull(temperature)) {
//            // 设置默认温度，这是 deepseek 官网给出的 Temperature 设置，通用对话设置为 1.3
//            aiChatRequest.setTemperature(1.3);
//        }
    }
}
